import { useCallback, useEffect, useState } from 'react'
// import { getMenuList } from '../../api/user'
import { useSelector } from 'react-redux'
import { Menu } from 'antd'
import { MenuItem } from './model'
import { MenuType } from '../../mock/model'
import { icons } from './config'
// 导入 authSlice 中的 setMenuList action
// import { setMenus } from '../../store/authSlice'
import { useLocation, useNavigate } from 'react-router-dom'

function SideBar() {
  // const dispatch = useDispatch()
  const location = useLocation()
  const navigate = useNavigate()
  // const token = useSelector((state: any) => state.userSlice.token)
  const menus = useSelector((state: any) => state.authSlice.menuList)
  const [menuList, setMenuList] = useState<MenuItem[]>([])
  // 使用 useCallback 的目的是解决 useEffect 的依赖报错:  Either include it or remove the dependency array. eslintreact-hooks/exhaustive-deps
  const transformMenu = useCallback((menuList: MenuType[]): any => {
    return menuList.map((item: MenuType) => {
      return {
        key: item.key,
        label: item.label,
        icon: (item.icon && icons[item.icon]) || null,
        children: (item.children && transformMenu(item.children)) || null
      }
    })
  }, [])

  useEffect(() => {
    // if (!token) {
    //   return
    // }
    // getMenuList({ token }).then((res: any) => {
    //   if (res && !res.menuList) {
    //     return
    //   }
    //   // 将返回的菜单保存到 redux 中
    //   dispatch(setMenus(res.menuList))
    //   const finalMenu = transformMenu(res.menuList)
    //   setMenuList(finalMenu)
    // })
    const finalMenu = transformMenu(menus)
    setMenuList(finalMenu)
  }, [menus, transformMenu])

  // 修改为: 从 redux 中获取 menu

  const changeRoute = ({ key }: { key: string }) => {
    navigate(key)
  }

  const [openKeys, setOpenKeys] = useState([''])
  useEffect(() => {
    // 将 pathname 进行 / 分割成数组 ['a', 'b'], 然后将数组转换成['/a', '/a/b']
    const paths = location.pathname.split('/').filter((item) => item !== '')
    const transformedArray = paths.reduce((acc: any[], cur, index) => {
      const prevPath = index === 0 ? '' : acc[index - 1]
      acc.push(`${prevPath}/${cur}`)
      return acc
    }, [])
    setOpenKeys(transformedArray)
  }, [location.pathname])

  return (
    <>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={['/dashboard']}
        items={menuList}
        onClick={changeRoute}
        openKeys={openKeys}
        onOpenChange={setOpenKeys}
        selectedKeys={[location.pathname]}
      />
    </>
  )
}

export default SideBar
